#encoding=utf8
'''
Created on Oct 29, 2014

@author: jingyang <jingyang@smalltreemedia.com>
'''
from itertools import chain

from django.forms.widgets import CheckboxSelectMultiple, CheckboxInput
from django.utils.html import escape, format_html
from django.utils.text import Truncator
from django.contrib.admin.widgets import FilteredSelectMultiple,\
    ForeignKeyRawIdWidget
from django.utils.safestring import mark_safe
from django.utils.encoding import force_text

from suit.widgets import AutosizedTextarea
from django import forms
from sorl.thumbnail.shortcuts import get_thumbnail


class CustomTextarea(AutosizedTextarea):
    def __init__(self, attrs=None):
        default_attrs = {'rows': 1, 'style': '''overflow: hidden;
            word-wrap: break-word; resize: horizontal; width: 800px; height: 46px;'''}
        if attrs:
            default_attrs.update(attrs)
        super(CustomTextarea, self).__init__(default_attrs)


class CustomCheckboxSelectMultiple(CheckboxSelectMultiple):
    def render(self, name, value, attrs=None, choices=()):
        """
        override the render function for fixing the bug.
        """
        value = str(value).replace('[', '').replace(']', '').replace("u'", '')\
            .replace("'", '').split(', ')

        if value is None:
            value = []
        has_id = attrs and 'id' in attrs
        final_attrs = self.build_attrs(attrs, name=name)
        output = ['<ul>']
        # Normalize to strings
        str_values = set([force_text(v) for v in value])
        for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
            # If an ID attribute was given, add a numeric index as a suffix,
            # so that the checkboxes don't all have the same ID attribute.
            if has_id:
                final_attrs = dict(final_attrs, id='')
                label_for = format_html(' for="{0}"', final_attrs['id'])
            else:
                label_for = ''

            cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
            option_value = force_text(option_value)
            rendered_cb = cb.render(name, option_value)
            option_label = force_text(option_label)
            output.append(format_html('<li><label{0}>{1} {2}</label></li>',
                                      label_for, rendered_cb, option_label))
        output.append('</ul>')
        return mark_safe('\n'.join(output))


class CustomFilteredSelectMultiple(FilteredSelectMultiple):

    def media(self):
        return None


class CustomForeignKeyRawIdWidget(ForeignKeyRawIdWidget):
    def label_for_value(self, value):
        key = self.rel.get_related_field().name
        try:
            obj = self.rel.to._default_manager.using(self.db).get(**{key: value})
            return "<a title='click to view detail' id='id_now_name' target='_blank' href='/admin/%s/%s/%s/'>%s</a>" % \
                (self.rel.to._meta.app_label, self.rel.to._meta.module_name,
                 obj.pk, escape(Truncator(obj).words(14, truncate='...')))
        except (ValueError, self.rel.to.DoesNotExist):
            return ''


class CustomAdminImageWidget(forms.ClearableFileInput):

    template_with_initial = '%(clear_template)s<br />%(input_text)s: %(input)s'
    template_with_clear = ('<label style="width:auto" for="%(clear_checkbox_id)s">'
                           '')

    class Media:
        js = ("highslide/highslide-with-gallery.js",
              "base/js/highslide-override-config.js",)
        css = {'all': ('highslide/highslide.css',)}

    def render(self, name, value, attrs=None):
        output = super(CustomAdminImageWidget, self).render(name, value, attrs)
        if value and hasattr(value, 'url'):
            ext = 'JPEG'
            try:
                aux_ext = str(value).split('.')
                if aux_ext[len(aux_ext) - 1].lower() == 'png':
                    ext = 'PNG'
            except:
                pass
            try:
                mini = get_thumbnail(value, 'x80', upscale=False, format=ext)
            except Exception as e:
                print "Unable to get the thumbnail: ", e
            else:
                try:
                    output = (
                        '<div style="float:left">'
                        '<a title="Click to enlarge" style="width:%spx;display:block;margin:0 0 10px" class="thumbnail highslide" '
                        'href="%s" onclick="return hs.expand(this)">'
                        '<img src="%s"></a>%s</div>'
                    ) % (mini.width, value.url, mini.url, output)
                except AttributeError:
                    pass
        return mark_safe(output)
